package com.lsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lsb.pojo.User;
import com.lsb.mapper.UserMapper;
import com.lsb.response.Result;
import com.lsb.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsb.utils.MyJsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liusibo
 * @since 2021-06-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    PasswordEncoder encoder;

    @Override
    public List<User> getAllUsersIgnoreLogicDelete() {
        return userMapper.getAllUsersIgnoreLogicDelete();
    }

    @Override
    public User getUserByIdIgnoreLogicDelete(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public int updateUserByIdIgnoreLogicDelete(Integer id) {
        return userMapper.updateUserByIdIgnoreLogicDelete(id);
    }

    @Override
    public void modifyPersonalInformation(LinkedHashMap<String, String> map, HttpServletResponse response) throws Exception {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //查找是否存在该学号的用户
        wrapper.eq(User::getUsername,map.get("username"));
        User user = userMapper.selectOne(wrapper);
        System.out.println(user);
        if(user==null){
            //不存在的账户或者被锁定的账户会走这里，统一显示用户不存在给前端
            Result result = Result.error().message("用户不存在或账户被锁定");
            MyJsonUtils.WriteJSON(response,result);
        }
        else if(encoder.matches(map.get("password"),user.getPassword())
                && map.get("newPassword").equals(map.get("confirmPassword"))){
            user.setPassword(encoder.encode(map.get("newPassword")));
            user.setTelephoneNumber(map.get("telephoneNumber"));
            int flag = 0;
            try {
                flag = userMapper.updateById(user);
            } catch (Exception e) {
                Result result = Result.error().message("手机号码重复");
                MyJsonUtils.WriteJSON(response,result);
            }
            if(flag==1){
                Result result = Result.ok();
                MyJsonUtils.WriteJSON(response,result);
            }
        }
        else {
            Result result = Result.error().message("密码错误或数据格式错误");
            MyJsonUtils.WriteJSON(response,result);
        }

    }

}
